#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 有时依赖 libdmtx0a的库，需要先安装此库 sudo apt-get install libdmtx0a
# pip3 install pylibdmtx

# use:
#     from dmatrix import DMatrix
#     dm = DMatrix()
#     img = cv2.imread('./img/test.jpg')
#     print('code-->', dm.dmatrix(img))

import numpy
from pylibdmtx import pylibdmtx


class DMatrix:
    '''
        params:
            timeout: default 5ms, 单位秒，超时则返回 None (源图)
            max_count: default 1, 一般不用修改
    '''

    def __init__(self, timeout=0.005, max_count=1):
        self.timeout = int(timeout * 1000)
        self.max_count = max_count

    # 识别图片中的code码： img为cv读取的图片，返回识别到的结果（结果中可能会包含换行符）
    def dmatrix(self, img=None):
        if img is None or type(img) is not numpy.ndarray:
            raise Exception('please input img of cv !')
        code = pylibdmtx.decode(img, timeout=self.timeout, max_count=self.max_count)
        return code[0].data.decode('utf-8') if len(code) > 0 else None
